package com.example.demo.config;

import com.example.demo.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

//设置登录拦截器
@Component
public class  LoginInterCeptor implements HandlerInterceptor {

    @Autowired
    private static Logger log = LoggerFactory.getLogger(LoginInterCeptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证session是否合法
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("user");
        if (user == null) {
            //为空代表没登陆过,才可以通行
            log.warn("用户未登录,请求被拦截器拦截");
            return false;
        }
        return true;
    }
}